<template>
  <div class="assign-homework-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <button @click="goBack" class="back-btn">← 返回管理中心</button>
        <h1 class="page-title">布置作业</h1>
        <p class="page-subtitle">为学生布置编程作业</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="container">
        <!-- 搜索区域 -->
        <div class="search-section">
          <div class="search-container">
            <!-- 搜索表单 -->
            <div class="search-row">
              <div class="form-group">
                <label>查</label>
                <input 
                  v-model="searchForm.search" 
                  type="text" 
                  placeholder="请输入关键词"
                  class="form-input"
                />
              </div>
              
              <button @click="searchHomework" class="search-btn">搜索</button>
            </div>

            <!-- 右侧按钮组 -->
            <div class="action-buttons">
              <button @click="refreshHomework" :disabled="isRefreshing" class="refresh-btn">
                <span v-if="isRefreshing">⏳ 刷新中...</span>
                <span v-else>🔄 刷新</span>
              </button>
          <button @click="createHomework" class="create-homework-btn">新建作业</button>
            </div>
          </div>
        </div>

        <!-- 作业列表标题 -->
        <div class="list-header">
          <h2 class="list-title">📚 我的班级作业列表</h2>
        </div>

        <!-- 作业表格 -->
        <div class="table-container">
          <table class="homework-table">
            <thead>
              <tr>
                <th>序号</th>
                <th>作业名称</th>
                <th>开始时间</th>
                <th>结束时间</th>
                <th>所属班级</th>
                <th>状态</th>
                <th>创建人</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="homeworks.length === 0">
                <td colspan="8" class="empty-row">
                  暂无数据
                </td>
              </tr>
              <template v-for="(homework, index) in homeworks" :key="homework.id">
                <tr class="table-row">
                <td>{{ index + 1 }}</td>
                <td class="title-cell">{{ homework.title }}</td>
                <td>{{ formatDate(homework.startTime) }}</td>
                <td>{{ formatDate(homework.endTime) }}</td>
                <td>{{ homework.className || '未指定班级' }}</td>
                <td>
                    <span :class="getStatusClass(homework.statusDesc || homework.status)">{{ homework.statusDesc || homework.status }}</span>
                </td>
                <td>{{ homework.creator || homework.teacherName || '当前用户' }}</td>
                <td class="action-cell">
                  <button @click="viewHomework(homework)" :disabled="isViewing" class="action-btn view-btn">
                      <span v-if="isViewing && expandedHomeworkId === homework.id">查看中...</span>
                      <span v-else-if="expandedHomeworkId === homework.id">收起</span>
                    <span v-else>查看</span>
                  </button>
                  <button @click="editHomework(homework)" class="action-btn edit-btn">编辑</button>
                  <button @click="deleteHomework(homework)" class="action-btn delete-btn">删除</button>
                </td>
              </tr>
                <!-- 作业详情二级区块 -->
                <tr v-if="expandedHomeworkId === homework.id" class="detail-row">
                  <td colspan="8" class="detail-cell">
                    <div class="homework-detail">
                      <div v-if="homeworkDetail && homeworkDetail.id === homework.id" class="detail-content">
                        <h3 class="detail-title">📋 作业详情</h3>
                        <div class="detail-grid">
                          <div class="detail-item">
                            <label>作业ID：</label>
                            <span>{{ homeworkDetail.id }}</span>
                          </div>
                          <div class="detail-item">
                            <label>作业名称：</label>
                            <span>{{ homeworkDetail.title || homework.title }}</span>
                          </div>
                          <div class="detail-item">
                            <label>开始时间：</label>
                            <span>{{ homeworkDetail.startTime || homework.startTime }}</span>
                          </div>
                          <div class="detail-item">
                            <label>结束时间：</label>
                            <span>{{ homeworkDetail.endTime || homework.endTime }}</span>
                          </div>
                          <div class="detail-item">
                            <label>状态：</label>
                            <span :class="getStatusClass(homeworkDetail.statusDesc || homeworkDetail.status || homework.status)">
                              {{ homeworkDetail.statusDesc || homeworkDetail.status || homework.status }}
                            </span>
                          </div>
                          <div class="detail-item">
                            <label>题数量：</label>
                            <span>{{ homeworkDetail.questions?.length || homework.questionCount || homework.questions?.length || 0 }}</span>
                          </div>
                          <div class="detail-item">
                            <label>报名数：</label>
                            <span>{{ homeworkDetail.submitCount || homework.submitCount || homeworkDetail.registrationCount || 0 }}</span>
                          </div>
                          <div class="detail-item">
                            <label>创建人：</label>
                            <span>{{ homeworkDetail.teacherName || homework.teacherName || homeworkDetail.creator || '当前用户' }}</span>
                          </div>
                          <div class="detail-item">
                            <label>总分：</label>
                            <span>{{ homeworkDetail.totalScore || 100 }}</span>
                          </div>
                          <div class="detail-item">
                            <label>总学生数：</label>
                            <span>{{ homeworkDetail.totalStudents || 0 }}</span>
                          </div>
                          <div class="detail-item full-width" v-if="homeworkDetail.description">
                            <label>作业描述：</label>
                            <div class="description-text">{{ homeworkDetail.description }}</div>
                          </div>
                        </div>
                      </div>
                      <div v-else class="loading-detail">
                        <div class="loading-spinner"></div>
                        <span>正在加载作业详情...</span>
                      </div>
                    </div>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <div class="pagination">
            <span class="page-info">(共 {{ totalCount }} 条)</span>
            <button 
              @click="goToPage(currentPage - 1)"
              :disabled="currentPage <= 1"
              class="page-btn"
            >
              上一页
            </button>
            <span class="current-page">{{ currentPage }}</span>
            <button 
              @click="goToPage(currentPage + 1)"
              :disabled="currentPage >= totalPages"
              class="page-btn"
            >
              下一页
            </button>
            <!-- 页码跳转 -->
            <div class="page-jump">
              <span class="jump-label">跳转到</span>
              <input 
                v-model.number="jumpToPageNumber" 
                type="number" 
                min="1" 
                :max="totalPages"
                placeholder="页码"
                class="jump-input"
                @keyup.enter="jumpToPage"
              />
              <span class="jump-label">页</span>
              <button @click="jumpToPage" class="jump-btn">跳转</button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/config'
import API_CONFIG from '@/api/apiConfig'
import { getHomeworkDetail, publishHomework as publishHomeworkAPI, deleteHomework as deleteHomeworkAPI, copyHomework } from '@/api/homework'
import { getCurrentUserId, compareUserIds, isMyHomework, formatUserId } from '@/utils/userIdUtils'
import logger from '../utils/logger.js'

export default {
  name: 'AssignHomework',
  setup() {
    // Vue Router
    const router = useRouter()
    
    // 响应式数据
    const homeworks = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const totalCount = ref(0)
    const pageSize = 10
    const isRefreshing = ref(false)
    const isViewing = ref(false)
    const expandedHomeworkId = ref(null) // 当前展开的作业ID
    const homeworkDetail = ref(null) // 当前作业的详情数据
    const jumpToPageNumber = ref(null) // 跳转页码

    // 搜索表单
    const searchForm = reactive({
      grade: '',
      title: '',
      startTime: '',
      search: ''
    })

    // 模拟数据（空列表）
    const mockHomeworks = []

    // 🔥 统一的数据加载方法 - 所有操作都使用 /goc/homework/list 接口
    const loadHomeworksUnified = async (page = null, keyword = null) => {
      try {
        // 如果传入了page参数，则更新当前页码
        if (page !== null) {
          currentPage.value = page
        }
        
        // 如果传入了keyword参数，则更新搜索关键词
        if (keyword !== null) {
          searchForm.search = keyword
        }
        
        logger.log('📚 [AssignHomework] 统一加载作业列表')
        logger.log('🌐 [AssignHomework] 调用接口: /goc/homework/list')
        logger.log('📊 [AssignHomework] 请求参数 - page:', currentPage.value, 'keyword:', searchForm.search || '(无)')
        
        // 构建请求参数
        const params = {
          page: currentPage.value,  // integer类型
          size: pageSize
        }
        
        // 添加关键词搜索参数（如果有）
        if (searchForm.search && searchForm.search.trim()) {
          params.keyword = searchForm.search.trim()  // string类型
          logger.log('🔍 [AssignHomework] 添加搜索关键词:', params.keyword)
        }
        
        // 调用作业列表API
        const apiPath = '/goc/homework/list'
        logger.log('🔧 [AssignHomework] API路径:', apiPath)
        logger.log('🔧 [AssignHomework] 完整请求参数:', params)
        
        const response = await api.get(apiPath, { params })
        
        logger.log('✅ [AssignHomework] 作业列表加载成功:', response.data)
        
        // 处理响应数据 - 根据实际返回结构判断
        if (response.data && response.data.code === 0 && response.data.data) {
          // 标准API响应结构：{code, message, data: {records, total, ...}}
          logger.log('✅ [LoadHomeworks] 进入标准API响应分支')
          const responseData = response.data.data
          homeworks.value = await Promise.all((responseData.records || []).map(mapHomeworkData))
          totalCount.value = responseData.total || 0
          totalPages.value = Math.ceil(totalCount.value / pageSize)
        } else if (response.data && response.data.records) {
          // 直接分页数据结构：{records, total, size, current, pages}
          logger.log('✅ [LoadHomeworks] 进入直接分页数据分支')
          homeworks.value = await Promise.all((response.data.records || []).map(mapHomeworkData))
          totalCount.value = response.data.total || 0
          totalPages.value = Math.ceil(totalCount.value / pageSize)
          
          logger.log('📋 [AssignHomework] 解析后的作业列表:', homeworks.value)
          logger.log('📊 [AssignHomework] 总数:', totalCount.value, '总页数:', totalPages.value)
        } else {
          logger.warn('⚠️ [AssignHomework] API返回异常:', response.data)
          // 保留原有的本地数据逻辑作为降级方案
          const savedHomeworks = JSON.parse(localStorage.getItem('homeworkList') || '[]')
          homeworks.value = savedHomeworks
          totalCount.value = savedHomeworks.length
          totalPages.value = Math.ceil(totalCount.value / pageSize)
        }
        
      } catch (error) {
        logger.error('❌ [AssignHomework] 加载作业列表失败:', error)
        
        // 降级到本地数据
        const savedHomeworks = JSON.parse(localStorage.getItem('homeworkList') || '[]')
        homeworks.value = savedHomeworks
        totalCount.value = savedHomeworks.length
        totalPages.value = Math.ceil(totalCount.value / pageSize)
      }
    }
    
    // 兼容旧代码的方法
    const loadHomeworks = () => loadHomeworksUnified()

    const searchHomework = async () => {
      logger.log('🔍 [AssignHomework] 点击搜索按钮')
      logger.log('📋 [AssignHomework] 搜索关键词:', searchForm.search)
      
      // 重置到第一页，使用当前搜索关键词
      currentPage.value = 1
      await loadHomeworksUnified(1, searchForm.search)
    }

    const createHomework = () => {
      logger.log('新增作业')
      // 跳转到作业创建页面
      window.location.href = '#/homework/create'
    }

    const refreshHomework = async () => {
      if (isRefreshing.value) return // 防止重复刷新
      
      try {
        isRefreshing.value = true
        logger.log('🔄 [AssignHomework] 刷新作业列表')
        
        // 重置搜索表单和页码
        searchForm.grade = ''
        searchForm.title = ''
        searchForm.startTime = ''
        searchForm.search = ''
        currentPage.value = 1
        
        // 调用统一接口 /goc/homework/list
        await loadHomeworksUnified(1, '')
        
        logger.log(`📊 [AssignHomework] 刷新完成: 共${totalCount.value}条作业`)
        
      } catch (error) {
        logger.error('❌ [AssignHomework] 刷新作业列表失败:', error)
        await loadHomeworks()
      } finally {
        isRefreshing.value = false
      }
    }

    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
    }

    const getStatusClass = (status) => {
      switch (status) {
        case '草稿':
        case '未发布':
          return 'status-unpublished'
        case '已发布':
        case '进行中':
          return 'status-ongoing'
        case '已结束':
        case '已截止':
          return 'status-ended'
        case 0:  // 草稿状态
          return 'status-unpublished'
        case 1:  // 已发布状态
          return 'status-ongoing'
        case 2:  // 已截止状态
          return 'status-ended'
        default:
          return 'status-default'
      }
    }

    const goToPage = async (page) => {
      if (page >= 1 && page <= totalPages.value) {
        logger.log('📄 [AssignHomework] 翻页到第', page, '页')
        // 使用统一接口，传递页码和当前搜索关键词
        await loadHomeworksUnified(page, searchForm.search)
      }
    }
    
    // 🔥 页码跳转功能
    const jumpToPage = async () => {
      const targetPage = jumpToPageNumber.value
      
      if (!targetPage) {
        alert('请输入页码')
        return
      }
      
      if (targetPage < 1 || targetPage > totalPages.value) {
        alert(`请输入有效的页码（1-${totalPages.value}）`)
        jumpToPageNumber.value = null
        return
      }
      
      logger.log('🎯 [AssignHomework] 跳转到第', targetPage, '页')
      
      // 使用统一接口跳转
      await loadHomeworksUnified(targetPage, searchForm.search)
      
      // 清空输入框
      jumpToPageNumber.value = null
    }

    const editHomework = async (homework) => {
      logger.log('编辑作业:', homework)
      logger.log('🆔 [AssignHomework] 作业ID:', homework.id)
      
      try {
        // 存储作业ID到localStorage作为备用
        localStorage.setItem('editingHomeworkId', homework.id)
        
        // 跳转到作业编辑页面，通过URL参数传递ID
        window.location.href = `#/homework/edit/${homework.id}`
        
      } catch (error) {
        logger.error('❌ [AssignHomework] 跳转编辑页面失败:', error)
        alert('跳转编辑页面失败，请稍后重试')
      }
    }

    const viewHomework = async (homework) => {
      logger.log('🔍 [AssignHomework] 查看作业详情，跳转到查看页面')
      logger.log('🆔 [AssignHomework] 作业ID:', homework.id)
      
      try {
        // 🔥 跳转到教师端作业查看页面
        router.push({
          path: `/teacher-homework-view/${homework.id}`
        })
      } catch (error) {
        logger.error('❌ [AssignHomework] 跳转失败:', error)
        alert('跳转失败，请稍后重试')
      }
      return
      
      // 以下代码已废弃，改为跳转到独立页面
      /*
      // 如果当前作业已经展开，则收起
      if (expandedHomeworkId.value === homework.id) {
        expandedHomeworkId.value = null
        homeworkDetail.value = null
        return
      }
      
      if (isViewing.value) return // 防止重复点击
      
      try {
        isViewing.value = true
        expandedHomeworkId.value = homework.id
        homeworkDetail.value = null // 清空之前的详情数据
        
        logger.log('🔍 [AssignHomework] 查看作业详情:', homework)
        logger.log('🔍 [AssignHomework] 作业对象的所有属性:', Object.keys(homework))
        logger.log('🔍 [AssignHomework] homework.id:', homework.id)
        logger.log('🔍 [AssignHomework] homework的完整结构:', JSON.stringify(homework, null, 2))
        logger.log('🔍 [AssignHomework] homework对象详细信息:')
        logger.log('  - 类型:', typeof homework)
        logger.log('  - 是否为数组:', Array.isArray(homework))
        logger.log('  - 构造函数:', homework.constructor.name)
        logger.log('  - 所有属性值:')
        Object.keys(homework).forEach(key => {
          logger.log(`    ${key}: ${homework[key]} (类型: ${typeof homework[key]})`)
        })
        logger.log('🌐 [AssignHomework] 调用作业详情接口:', API_CONFIG.getFullURL(API_CONFIG.ENDPOINTS.HOMEWORK_DETAIL))
        
        // 获取作业ID（后端返回的数据中ID字段就是 id）
        const actualId = homework.id
        
        logger.log('� [AssignHomework] 作业ID:', actualId)
        logger.log('🔍 [AssignHomework] 作业ID类型:', typeof actualId)
        logger.log('🔍 [AssignHomework] 作业ID是否为数字:', !isNaN(actualId))
        logger.log('🔍 [AssignHomework] 作业ID是否为空:', actualId === null || actualId === undefined)
        logger.log('🔍 [AssignHomework] 作业ID转换为字符串:', String(actualId))
        logger.log('🔍 [AssignHomework] 作业ID转换为数字:', Number(actualId))
        logger.log('🔍 [AssignHomework] 作业ID是否为整数:', Number.isInteger(actualId))
        logger.log('🔍 [AssignHomework] 作业ID的原始值:', actualId)
        logger.log('🔍 [AssignHomework] 作业ID的JSON字符串:', JSON.stringify(actualId))
        logger.log('🔍 [AssignHomework] 点击的作业ID是:', actualId, '类型:', typeof actualId)
        
        if (!actualId) {
          logger.error('❌ [AssignHomework] 作业ID不存在')
          alert('作业ID不存在，无法查看详情')
          expandedHomeworkId.value = null
          return
        }
        
        // 调用作业详情接口（不需要/api前缀）
        logger.log('🌐 [AssignHomework] API路径:', API_CONFIG.ENDPOINTS.HOMEWORK_DETAIL)
        logger.log('🔑 [AssignHomework] 令牌将通过拦截器自动添加到Authorization请求头')
        logger.log('📝 [AssignHomework] 传入作业ID:', actualId)
        logger.log('获取到的实际作业id是',actualId)
        
        const response = await getHomeworkDetail(actualId)
        
        logger.log('✅ [AssignHomework] 作业详情接口调用成功')
        logger.log('📄 [AssignHomework] 响应数据:', response)
        logger.log('📄 [AssignHomework] 响应数据code:', response?.code)
        logger.log('📄 [AssignHomework] 响应数据data:', response?.data)
        
        // 处理响应数据
        // 注意：axios响应拦截器已经返回了response.data，所以这里的response就是后端返回的数据
        if (response && response.code === 0) {  // 后端返回code: 0表示成功
          logger.log('✅ [AssignHomework] 进入成功分支')
          const detailData = response.data  // 作业详情在response.data中
          logger.log('📋 [AssignHomework] 作业详情数据:', detailData)
          
          // 将详情数据存储到响应式变量中
          homeworkDetail.value = {
            ...detailData,
            id: homework.id // 确保ID一致
          }
          logger.log('✅ [AssignHomework] 作业详情数据已存储到 homeworkDetail.value:', homeworkDetail.value)
        } else {
          logger.warn('⚠️ [AssignHomework] 作业详情API返回异常:', response)
          logger.warn('⚠️ [AssignHomework] 条件判断失败:')
          logger.warn('  - response 存在:', !!response)
          logger.warn('  - response.code:', response?.code)
          logger.warn('  - response.code === 0:', response?.code === 0)
          alert('获取作业详情失败，请稍后重试')
          expandedHomeworkId.value = null
        }
        
      } catch (error) {
        logger.error('❌ [AssignHomework] 查看作业详情失败:', error)
        alert('查看作业详情失败，请稍后重试')
        expandedHomeworkId.value = null
      } finally {
        isViewing.value = false
      }
      */
    }

    const deleteHomework = async (homework) => {
      logger.log('🗑️ [DeleteHomework] 开始删除作业:', homework)
      logger.log('🗑️ [DeleteHomework] 作业ID:', homework.id)
      logger.log('🗑️ [DeleteHomework] 作业标题:', homework.title)
      
      if (confirm(`确定要删除作业"${homework.title}"吗？删除后将无法恢复。`)) {
        try {
          logger.log('🗑️ [DeleteHomework] 即将调用删除API，作业ID:', homework.id)
          
          const response = await deleteHomeworkAPI(homework.id)
          
          logger.log('✅ [DeleteHomework] API调用完成，响应数据:', response)
          logger.log('✅ [DeleteHomework] 响应数据类型:', typeof response)
          logger.log('✅ [DeleteHomework] 响应数据JSON:', JSON.stringify(response))
          
          // 注意：由于响应拦截器返回response.data，这里的response实际上是后端返回的数据
          // 检查业务状态码 - 根据你之前的反馈，删除成功应该是code: 0
          if (response && response.code === 0) {
            logger.log('✅ [DeleteHomework] 业务状态码正常，删除成功')
            logger.log('✅ [DeleteHomework] 后端消息:', response.message)
            logger.log('✅ [DeleteHomework] 后端数据:', response.data)
            
            // 移除成功提示，直接执行删除操作以改善用户体验
            // const successMessage = response.data || response.message || '作业删除成功！'
            // alert(successMessage)
              
              // 从本地列表中移除已删除的作业
              logger.log('🔍 [DeleteHomework] 当前列表中的作业数量:', homeworks.value.length)
              logger.log('🔍 [DeleteHomework] 要删除的作业ID:', homework.id, '类型:', typeof homework.id)
              logger.log('🔍 [DeleteHomework] 当前列表中的所有作业ID:', homeworks.value.map(h => ({ id: h.id, title: h.title })))
              
              const homeworkIndex = homeworks.value.findIndex(h => h.id === homework.id)
              logger.log('🔍 [DeleteHomework] 找到的作业索引:', homeworkIndex)
              
              if (homeworkIndex !== -1) {
                const removedHomework = homeworks.value.splice(homeworkIndex, 1)
                logger.log('✅ [DeleteHomework] 已从本地列表中移除作业:', removedHomework[0])
                logger.log('✅ [DeleteHomework] 移除后列表长度:', homeworks.value.length)
              } else {
                logger.error('❌ [DeleteHomework] 在本地列表中找不到要删除的作业ID:', homework.id)
              }
              
              // 更新总数
              totalCount.value = Math.max(0, totalCount.value - 1)
              totalPages.value = Math.ceil(totalCount.value / 10) // 假设每页10条
              
              // 如果当前页没有数据了，回到上一页
              if (homeworks.value.length === 0 && currentPage.value > 1) {
                currentPage.value = currentPage.value - 1
                await loadHomeworks()
              }
              
              logger.log('✅ [DeleteHomework] 本地状态已更新')
            } else {
              logger.error('❌ [DeleteHomework] 业务状态码异常:', response)
              alert('删除失败：' + (response?.message || '业务处理失败'))
            }
        } catch (error) {
          logger.error('❌ [DeleteHomework] 删除失败，错误:', error)
          alert('删除失败：' + (error.response?.data?.message || error.message || '网络错误'))
        }
      }
    }



    // 班级信息缓存
    const teamCache = ref({})
    
    // 根据teamId获取班级名称
    const getTeamName = async (teamId) => {
      if (!teamId) return '未指定班级'
      
      // 检查缓存
      if (teamCache.value[teamId]) {
        return teamCache.value[teamId]
      }
      
      try {
        // 动态导入team API
        const { teamApi } = await import('@/api/team')
        const response = await teamApi.findById(teamId)
        
        if (response && response.code === 0 && response.data) {
          const teamData = Array.isArray(response.data) ? response.data[0] : response.data
          const teamName = teamData.teamName || teamData.name || '未命名班级'
          
          // 缓存班级名称
          teamCache.value[teamId] = teamName
          
          return teamName
        }
      } catch (error) {
        logger.error('❌ [AssignHomework] 获取班级名称失败:', error)
      }
      
      return '未指定班级'
    }
    
    // 数据映射方法，统一处理后端返回的作业数据格式
    const mapHomeworkData = async (homework) => {
      // 如果className为空，尝试通过teamId获取
      let className = homework.className || homework.teamName
      
      if (!className && homework.teamId) {
        className = await getTeamName(homework.teamId)
      }
      
      return {
        ...homework,
        // 统一字段映射
        questionCount: homework.questionCount || homework.questions?.length || 0,
        registrationCount: homework.registrationCount || homework.submitCount || 0,
        creator: homework.creator || homework.teacherName || '当前用户',
        className: className || '未指定班级'
      }
    }

    const goBack = () => {
      // 返回管理中心
      router.push('/management')
    }

    // 生命周期
    onMounted(() => {
      // 检查是否需要刷新数据
      const needsRefresh = localStorage.getItem('homeworkListNeedsRefresh')
      if (needsRefresh === 'true') {
        logger.log('🔄 [AssignHomework] 检测到刷新标记，强制刷新作业列表')
        localStorage.removeItem('homeworkListNeedsRefresh')
        // 使用刷新方法而不是普通加载，确保获取最新数据
        refreshHomework()
      } else {
        loadHomeworks()
      }
    })

    return {
      homeworks,
      currentPage,
      totalPages,
      totalCount,
      searchForm,
      isRefreshing,
      isViewing,
      expandedHomeworkId,
      homeworkDetail,
      jumpToPageNumber,
      searchHomework,
      refreshHomework,
      createHomework,
      formatDate,
      getStatusClass,
      goToPage,
      jumpToPage,
      editHomework,
      viewHomework,
      deleteHomework,
      mapHomeworkData,
      goBack
    }
  }
}
</script>

<style scoped>
.assign-homework-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

/* 页面头部样式 */
.page-header {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  padding: 30px;
  margin-bottom: 30px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
}

.back-btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  margin-bottom: 20px;
  transition: background 0.2s;
}

.back-btn:hover {
  background: #2980b9;
}

.page-title {
  font-size: 32px;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 700;
}

.page-subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

/* 主要内容区域 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
}

.container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  padding: 30px;
}

/* 搜索区域 */
.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  gap: 20px;
  flex-wrap: wrap;
}

.search-row {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
  flex: 1;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-select,
.form-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.search-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 8px 24px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  height: 36px;
}

.search-btn:hover {
  background: #45a049;
}

/* 右侧按钮组 */
.action-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-shrink: 0;
}

.refresh-btn {
  background: #FF9800;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background 0.2s;
  height: 36px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.refresh-btn:hover:not(:disabled) {
  background: #F57C00;
}

.refresh-btn:disabled {
  background: #FFCC80;
  cursor: not-allowed;
  opacity: 0.7;
}

.create-homework-btn {
  background: #2196F3;
  color: white;
  border: none;
  padding: 8px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background 0.2s;
  height: 36px;
}

.create-homework-btn:hover {
  background: #1976D2;
}

/* 列表标题 */
.list-header {
  margin: 20px 0;
}

.list-title {
  font-size: 18px;
  color: #333;
  margin: 0;
  padding-left: 8px;
  border-left: 4px solid #4CAF50;
}

/* 表格样式 */
.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow-x: auto;
}

.homework-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1000px;
}

.homework-table th {
  background: #4CAF50;
  color: white;
  padding: 15px 10px;
  text-align: left;
  font-weight: 500;
  font-size: 14px;
  white-space: nowrap;
}

.homework-table td {
  padding: 15px 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #333;
}

.table-row:hover {
  background: #f9f9f9;
}

.title-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-cell {
  white-space: nowrap;
}

.action-btn {
  padding: 4px 8px;
  margin: 0 2px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.view-btn {
  background: #2196F3;
  color: white;
}

.edit-btn {
  background: #FF9800;
  color: white;
}

.delete-btn {
  background: #f44336;
  color: white;
}

.action-btn:hover {
  opacity: 0.8;
}

.empty-row {
  text-align: center;
  color: #999;
  padding: 40px 20px;
}

/* 状态样式 */
.status-unpublished {
  color: #FF9800;
  background: #FFF3E0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-ongoing {
  color: #4CAF50;
  background: #E8F5E8;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-ended {
  color: #757575;
  background: #F5F5F5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-default {
  color: #666;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  background: white;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.page-info {
  color: #666;
  font-size: 14px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
}

.page-btn:hover:not(:disabled) {
  background: #f5f5f5;
}

.page-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.current-page {
  background: #4CAF50;
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  min-width: 32px;
  text-align: center;
}

/* 页码跳转样式 */
.page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 15px;
  padding-left: 15px;
  border-left: 1px solid #e0e0e0;
}

.jump-label {
  font-size: 14px;
  color: #666;
}

.jump-input {
  width: 60px;
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
  transition: border-color 0.3s;
}

.jump-input:focus {
  outline: none;
  border-color: #4CAF50;
}

.jump-input:hover {
  border-color: #999;
}

/* 移除数字输入框的上下箭头 */
.jump-input::-webkit-inner-spin-button,
.jump-input::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.jump-input[type=number] {
  -moz-appearance: textfield;
}

.jump-btn {
  padding: 6px 16px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.jump-btn:hover {
  background: #45a049;
}

.jump-btn:active {
  background: #3d8b40;
}

/* 作业详情二级区块样式 */
.detail-row {
  background: #f8f9fa;
}

.detail-cell {
  padding: 0 !important;
  border: none !important;
}

.homework-detail {
  padding: 20px;
  background: #f8f9fa;
  border-top: 2px solid #4CAF50;
}

.detail-content {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.detail-title {
  color: #2c3e50;
  font-size: 18px;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #4CAF50;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item label {
  font-weight: 600;
  color: #555;
  min-width: 80px;
  flex-shrink: 0;
}

.detail-item span {
  color: #333;
  flex: 1;
}

.description-text {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  border-left: 3px solid #4CAF50;
  margin-top: 5px;
  white-space: pre-wrap;
  line-height: 1.5;
}

.loading-detail {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 40px;
  color: #666;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #4CAF50;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .assign-homework-page {
    padding: 10px;
  }
  
  .page-header {
    padding: 20px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .container {
    padding: 20px;
  }
  
  .search-container {
    flex-direction: column;
    gap: 15px;
  }
  
  .search-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .action-buttons {
    justify-content: center;
    width: 100%;
  }
  
  .homework-table {
    font-size: 12px;
  }
  
  .homework-table th,
  .homework-table td {
    padding: 8px;
  }
  
  /* 移动端分页样式优化 */
  .pagination {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .page-jump {
    margin-left: 0;
    padding-left: 0;
    border-left: none;
    margin-top: 10px;
    width: 100%;
    justify-content: center;
  }
  
  .jump-input {
    width: 70px;
  }
}
</style> 